<?php
namespace app\common\model;

use think\Model;
use app\common\traits\model\TraitModel;

class Messages extends Model
{
	use TraitModel;

	const READ_STATUS = 1;

	public function users()
	{
        return $this->hasMany('UserMessages');
	}
    public function createMsg($msg_info = [])
    {
    	if ($user_id = $msg_info['users_id']) {
    		if (is_numeric($user_id)) {
    			$user_id = [['users_id' => $user_id]];
    		}else{
    			$user_id = [];
    			foreach ($msg_info['users_id'] as $key => $value) {
    				$user_id[] = ['users_id' => $value];
    			}
    		}
    	}
        !isset($msg_info['vars']) && $msg_info['vars'] = '';
    	$msg_info['body'] = $this->parseTemplate($msg_info['body'], $msg_info['vars']);
    	return self::create($msg_info, true)->users()->saveAll($user_id) ? true : false;
    }
    private function getTemplate($template)
    {
    	$templates = [
    		'wish' => '您的心愿有人接单，请<a href="'.url('/wishs/index').'">查看</a>',
    		'wishuser' => '您的接单已被拒绝', 
    		'check' => '您已通过审核请<a href="'.url('/userinfo/personinfo').'">编辑</a>',
    		'ordercreate' => '订单已经生成 请尽快<a href="'.url('/order/%s').'">支付</a>！',
            'quitdeposits' => '您的订单 (%s) 退款成功，请到<a href="'.url('/order/orderlist','','','user').'">会员中心</a>查看详情！'
    	];
    	return isset($templates[$template]) ? $templates[$template] : $template;
    }
    private function parseTemplate($value, $vars = [])
    {
    	if (strpos($value, '@') === 0) {
    		$value = $this->getTemplate(substr($value, 1));
    	}
    	if (!empty($vars) && is_array($vars)) {
            if (key($vars) === 0) {
                array_unshift($vars, $value);
                $value = call_user_func_array('sprintf', $vars);
            } else {
                $replace = array_keys($vars);
                foreach ($replace as &$v) {
                    $v = "{:{$v}}";
                }
                $value = str_replace($replace, $vars, $value);
            }

        }
        return $value;
    }
}
